<template>
  <div class="banner-management">
    <div class="tab-content">
      <!-- 操作按钮 -->
      <div class="action-bar">
        <el-button type="primary" @click="handleUpload">
          <el-icon><Upload /></el-icon>
          上传轮播图
        </el-button>
        <el-button @click="fetchBannerList">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>

      <!-- 轮播图列表 -->
      <el-card class="table-card">
        <div v-loading="loading" class="banner-grid">
          <div 
            v-for="(banner, index) in bannerList" 
            :key="index" 
            class="banner-item"
          >
            <div class="banner-image-container">
              <el-image
                :src="getImageUrl(banner.url || banner)"
                :preview-src-list="[getImageUrl(banner.url || banner)]"
                fit="cover"
                class="banner-image"
                :loading="imageLoading"
                @error="handleImageError(banner.url || banner)"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                    <span>加载失败</span>
                  </div>
                </template>
              </el-image>
              <div class="banner-overlay">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleDelete(banner.url || banner)"
                  :loading="deleteLoading"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </div>
            <div class="banner-info">
              <p class="banner-url">{{ banner.url || banner }}</p>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <el-empty 
          v-if="!loading && bannerList.length === 0" 
          description="暂无轮播图"
          :image-size="120"
        />
      </el-card>
    </div>

    <!-- 上传对话框 -->
    <el-dialog 
      v-model="uploadDialogVisible" 
      title="上传轮播图" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        :before-remove="handleRemove"
        accept="image/*"
        list-type="picture"
        :limit="1"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将图片拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持jpg、jpeg、png、gif、bmp、webp格式，建议不超过10MB
          </div>
        </template>
      </el-upload>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmUpload"
            :loading="uploadLoading"
            :disabled="!selectedFile"
          >
            确认上传
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Refresh, Delete, Picture, UploadFilled } from '@element-plus/icons-vue'
import { getBannerList, uploadBanner, deleteBanner } from '@/api/banner'

export default {
  name: 'BannerManagement',
  components: {
    Upload,
    Refresh,
    Delete,
    Picture,
    UploadFilled
  },
  setup() {
    const loading = ref(false)
    const uploadLoading = ref(false)
    const deleteLoading = ref(false)
    const imageLoading = ref(false)
    const uploadDialogVisible = ref(false)
    const selectedFile = ref(null)
    const uploadRef = ref(null)
    const bannerList = ref([])

    // 获取轮播图列表
    const fetchBannerList = async () => {
      try {
        loading.value = true
        const response = await getBannerList()
        
        // axios拦截器返回response.data，所以response就是后端的完整响应对象
        if (response && response.success) {
          bannerList.value = response.data || []
          ElMessage.success(`${response.message || '获取轮播图列表成功'} (共${bannerList.value.length}张)`)
        } else {
          ElMessage.error(response?.message || '获取轮播图列表失败')
        }
      } catch (error) {
        console.error('获取轮播图列表失败:', error)
        ElMessage.error('获取轮播图列表失败')
      } finally {
        loading.value = false
      }
    }

    // 处理上传按钮点击
    const handleUpload = () => {
      uploadDialogVisible.value = true
      selectedFile.value = null
      // 清空上传组件
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
    }

    // 处理文件选择
    const handleFileChange = (file, fileList) => {
      // 检查文件大小
      if (file.size > 10 * 1024 * 1024) {
        ElMessage.error('文件大小不能超过10MB')
        return false
      }
      
      // 检查文件类型 - 更宽松的检查
      const isImage = file.type?.startsWith('image/') || 
                     /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(file.name)
      if (!isImage) {
        ElMessage.error('只能上传图片文件 (jpg, jpeg, png, gif, bmp, webp)')
        return false
      }
      
      selectedFile.value = file.raw
    }

    // 处理文件移除
    const handleRemove = () => {
      selectedFile.value = null
    }

    // 确认上传
    const confirmUpload = async () => {
      if (!selectedFile.value) {
        ElMessage.warning('请先选择图片')
        return
      }

      try {
        uploadLoading.value = true
        const formData = new FormData()
        formData.append('imageFile', selectedFile.value)

        const response = await uploadBanner(formData)
        
        if (response && response.success) {
          ElMessage.success(response.message || '上传成功')
          uploadDialogVisible.value = false
          
          // 延迟一下再获取列表，确保后端已经处理完成
          setTimeout(() => {
            fetchBannerList() // 重新获取列表
          }, 500)
        } else {
          ElMessage.error(response?.message || '上传失败')
        }
      } catch (error) {
        ElMessage.error('上传失败')
      } finally {
        uploadLoading.value = false
      }
    }

    // 删除轮播图
    const handleDelete = async (url) => {
      try {
        await ElMessageBox.confirm(
          '此操作将永久删除该轮播图，是否继续？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        deleteLoading.value = true
        const response = await deleteBanner(url)
        
        if (response && response.success) {
          ElMessage.success(response.message || '删除成功')
          fetchBannerList() // 重新获取列表
        } else {
          ElMessage.error(response?.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      } finally {
        deleteLoading.value = false
      }
    }

    // 获取完整的图片URL
    const getImageUrl = (url) => {
      if (!url) {
        return ''
      }
      
      if (url.startsWith('http')) {
        return url
      }
      
      // 使用相对路径，让Nginx代理到后端服务器
      const normalizedUrl = url.startsWith('/') ? url : `/${url}`
      return normalizedUrl
    }

    // 处理图片加载错误
    const handleImageError = (url) => {
      console.error('图片加载失败:', getImageUrl(url))
    }

    onMounted(() => {
      fetchBannerList()
    })

    return {
      loading,
      uploadLoading,
      deleteLoading,
      imageLoading,
      uploadDialogVisible,
      selectedFile,
      uploadRef,
      bannerList,
      fetchBannerList,
      handleUpload,
      handleFileChange,
      handleRemove,
      confirmUpload,
      handleDelete,
      getImageUrl,
      handleImageError
    }
  }
}
</script>

<style scoped>
.banner-management {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.table-card {
  margin-top: 20px;
}

.banner-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.banner-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: box-shadow 0.3s;
}

.banner-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.banner-image-container {
  position: relative;
  height: 200px;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.banner-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.banner-item:hover .banner-overlay {
  opacity: 1;
}

.banner-info {
  padding: 12px;
  background: #f8f9fa;
}

.banner-url {
  margin: 0;
  font-size: 12px;
  color: #666;
  word-break: break-all;
  line-height: 1.4;
}

.image-slot {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.image-slot .el-icon {
  font-size: 30px;
  margin-bottom: 8px;
}

.upload-demo {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-upload__tip {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}
</style> 